package com.leps.nq.tx.core;

import com.leps.nq.common.exception.PlcOfflineException;
import com.leps.nq.common.exception.PlcPwdException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public abstract class AbstractRequest {
    public AbstractRequest(String ip, int port, String plcPwdStr) {
        this.ip = ip;
        this.port = port;
        this.plcPwdStr = plcPwdStr;
    }

    public String ip;
    public int port;
    public byte[] head;
    public String plcPwdStr;
    public byte[] tail;

    public final static int SOCKET_SO_TIMEOUT = 5000;

    public abstract byte[] getDatagram();

    public Response getResponse() throws PlcOfflineException, PlcPwdException {
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new PlcOfflineException(e);
        }
        try {
            socket.setSoTimeout(SOCKET_SO_TIMEOUT);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        try {
            OutputStream out = socket.getOutputStream();
            InputStream in = socket.getInputStream();
            out.write(this.getDatagram());
            if (this instanceof ReadRequest) {
                try {
                    byte[] b = new byte[256];
                    in.read(b);
                    return new Response(b);
                } catch (SocketTimeoutException e) {
                    throw new PlcPwdException("PLC密码错误", e);
                }
            }
        } catch (IOException e) {

        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
